import React, { createContext, useState, useContext, useEffect } from 'react';
import api from '../services/api';

const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 检查当前会话状态
  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        setLoading(true);
        const token = localStorage.getItem('token');
        
        if (!token) {
          setIsAuthenticated(false);
          setUser(null);
          setLoading(false);
          return;
        }
        
        // 设置Authorization头部
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        
        // 获取当前用户信息
        const response = await api.get('/auth/verify');
        
        if (response.data && response.data.user) {
          const userData = response.data.user;
          
          // 确保userId被正确保存
          if (!localStorage.getItem('userId') && userData.id) {
            localStorage.setItem('userId', userData.id.toString());
            localStorage.setItem('userRole', userData.role);
            console.log('验证时补充保存用户ID:', userData.id);
          }
          
          setUser(userData);
          setIsAuthenticated(true);
        } else {
          // 如果API返回错误信息，清除token
          localStorage.removeItem('token');
          localStorage.removeItem('userId');
          localStorage.removeItem('userRole');
          setIsAuthenticated(false);
          setUser(null);
        }
      } catch (err) {
        console.error('检查认证状态时出错:', err);
        // 清除所有认证相关数据
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('userRole');
        setIsAuthenticated(false);
        setUser(null);
        setError(err.response?.data?.message || '会话已过期，请重新登录');
      } finally {
        setLoading(false);
      }
    };

    checkAuthStatus();
  }, []);

  // 登录函数
  const login = async (username, password) => {
    try {
      setLoading(true);
      setError(null);
      
      // 记录登录尝试
      console.log(`尝试登录用户: ${username}`);
      
      const response = await api.post('/auth/login', { username, password });
      
      if (response.data && response.data.token) {
        const token = response.data.token;
        const userData = response.data.user;
        
        // 确保token完整保存
        console.log(`登录成功，获取到Token（长度${token.length}字符）`);
        console.log('用户数据:', userData);
        
        // 保存到本地存储，并确保保存成功
        localStorage.setItem('token', token);
        localStorage.setItem('userId', userData.id.toString()); // 确保保存用户ID
        localStorage.setItem('userRole', userData.role); // 也保存用户角色
        
        const savedToken = localStorage.getItem('token');
        const savedUserId = localStorage.getItem('userId');
        
        if (savedToken !== token) {
          console.error('Token保存失败，尝试重新保存');
          localStorage.removeItem('token');
          localStorage.setItem('token', token);
        }
        
        if (savedUserId !== userData.id.toString()) {
          console.error('UserId保存失败，尝试重新保存');
          localStorage.removeItem('userId');
          localStorage.setItem('userId', userData.id.toString());
        }
        
        console.log('保存的用户ID:', savedUserId);
        
        // 设置API请求头
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        
        // 检查是否为紧急模式token
        const isEmergencyMode = response.data.message && response.data.message.includes('应急模式');
        if (isEmergencyMode) {
          console.log('使用应急模式登录');
        }
        
        setUser(userData);
        setIsAuthenticated(true);
        return true;
      }
    } catch (err) {
      console.error('登录时出错:', err);
      
      // 尝试应急登录（仅限开发环境）
      if (username === 'admin' && window.location.hostname === 'localhost') {
        try {
          console.log('尝试使用应急模式登录');
          
          // 创建应急token（这只是临时解决方案）
          const emergencyToken = 'admin_emergency_token_' + Date.now();
          localStorage.setItem('token', emergencyToken);
          localStorage.setItem('userId', '1'); // 应急管理员ID
          localStorage.setItem('userRole', 'admin');
          api.defaults.headers.common['Authorization'] = `Bearer ${emergencyToken}`;
          
          // 设置虚拟用户信息
          const emergencyUser = {
            id: 1,
            username: 'admin',
            fullName: 'Emergency Admin',
            role: 'admin'
          };
          setUser(emergencyUser);
          setIsAuthenticated(true);
          
          console.log('应急模式登录成功，用户ID:', 1);
          
          return true;
        } catch (emergencyError) {
          console.error('应急登录失败:', emergencyError);
        }
      }
      
      setError(err.response?.data?.message || '用户名或密码错误');
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 登出函数
  const logout = () => {
    try {
      // 清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('userRole');
      // 移除授权头
      delete api.defaults.headers.common['Authorization'];
      // 更新状态
      setUser(null);
      setIsAuthenticated(false);
      console.log('用户已登出，清除所有本地数据');
    } catch (err) {
      console.error('登出操作失败:', err);
    }
  };

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    setUser(prev => ({ ...prev, ...newUserInfo }));
  };

  const value = {
    user,
    isAuthenticated,
    loading,
    error,
    login,
    logout,
    updateUserInfo
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

// 自定义钩子以简化上下文使用
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth必须在AuthProvider内部使用');
  }
  return context;
}; 